<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <button onclick="onclick">按钮</button>
    <script type="module">
      async function processTextStream({ stream, onTextPart }) {
        const reader = stream.pipeThrough(new TextDecoderStream()).getReader();
        while (true) {
          const { done, value } = await reader.read();
          if (done) {
            break;
          }
          await onTextPart(value);
        }
      }

      async function consumeStream({ stream, onError }) {
        const reader = stream.getReader();
        try {
          while (true) {
            const { done } = await reader.read();
            if (done) break;
          }
        } catch (error) {
          onError?.(error);
        } finally {
          reader.releaseLock();
        }
      }

      window.onclick = async () => {
        const response = await fetch(
          'http://localhost:2000/ai/chat/02',
          {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              messagesList: [
                {
                  role: 'user',
                  content: [
                    {
                      type: 'text',
                      text: '你好',
                    },
                    {
                      type: 'text',
                      text: '1+1=？',
                    },
                  ],
                },
              ],
              modelConfig: {
                streaming: true,
              },
              chatSessionId: 'xx',
            }),
          },
        );
        let result = '';
        await processTextStream({
          stream: response.body,
          onTextPart: (chunk) => {
            result += chunk;
            console.log(result,chunk,'<<<<')
            // setCompletion(result);
          },
        });

        // const reader = response.body.getReader();
        // let resPonseText = '';
        // while (true) {
        //   const { done, value } = await reader.read();
        //   if (done) {
        //     break;
        //   }
        //   const text = new TextDecoder().decode(value);

        //   const resText = text.split('\n\n').filter(Boolean);
        //   resText.forEach((item) => {
        //     const chunk = JSON.parse(item.replace(/^data:\s+/, '').trim());
        //     if (chunk.type === 'chunk') {
        //       resPonseText += chunk.content;
        //     }
        //     if (chunk.type === 'end') {
        //       console.log(chunk.chatSessionId, 'end');
        //     }
        //   });
        // }
      };
    </script>
  </body>
</html>
